package xyz.lxbq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.lxbq.pojo.Depart;
import xyz.lxbq.service.DepartServicr;
import xyz.lxbq.utils.PageUtils;
import xyz.lxbq.utils.ResultMessage;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author XuHu
 * @version 1.0
 * @date 2020/10/15 13:27
 */
@Controller
public class DepartController {
    @Autowired
    DepartServicr departServicr;

    /**
     * 添加部门
     */
    @RequestMapping("/addDepart")
    @ResponseBody  //将返回值转为JSON
    public ResultMessage addDepart(Depart depart, HttpSession session, HttpServletResponse response,String name,String createdate) throws Exception{
        ResultMessage message = null;
        response.setContentType("text/html;charset=utf-8");
        //存储新增部门
        Depart adDepart = new Depart(name, createdate);
        int i = departServicr.addDepare(adDepart);
        if (i == 1){
            //存session
            session.setAttribute("Depart",depart);
            message = new ResultMessage(200,"添加成功");
        }else{
            message = new ResultMessage(300,"添加失败");
        }
        return message;
    }

    //分页
    @RequestMapping("/departPageList/{pageIndex}/{pageSize}")
    String departPageList(@PathVariable("pageIndex") int pageIndex, @PathVariable("pageSize") int pageSize, Model model){
        int aLlDepareCount = departServicr.getALlDepareCount();//获取总行数
        List<Depart> departPage = departServicr.getDepartPage((pageIndex - 1) * pageSize, pageSize);//获取每页数据，并用于返回当前数据
        //封装工具类
        PageUtils pageUtils = new PageUtils(pageIndex,pageSize,aLlDepareCount,departPage);
        model.addAttribute("pageUtils",pageUtils);
        return "departlist";
    }


    /**
     * 删除部门
     */
    @RequestMapping("/deletedDepare")
    @ResponseBody
    public ResultMessage deletedDepare(HttpSession session, HttpServletResponse response,int id){
        ResultMessage message = null;
        response.setContentType("text/html;charset=utf-8");
        //判断是否删除
        int i = departServicr.deletedDepare(id);
        if (i == 1 ){
            message = new ResultMessage(200,"删除成功");
        }else{
            message = new ResultMessage(300,"删除失败");
        }
        return message;
    }

    /**
     * 获取所有部门信息
     */
    @RequestMapping("/getAllDepare")
    @ResponseBody
    public List<Depart> getAllDepare() {
        return departServicr.getAllDepare();
    }

}
